package cn.jinjimi.app.custom.ui.fragment;

import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.event.LocalEvent.CustomClueStaticUpdateEvent;
import cn.jinjimi.app.custom.event.ClueAddCustomSucEvent;
import cn.jinjimi.app.custom.event.ClueUpdateEvent;
import cn.jinjimi.app.custom.event.CustomChangeEvent;
import cn.jinjimi.app.custom.event.CustomClueRefreshEvent;
import cn.jinjimi.app.custom.ui.adapter.CustomClueListAdapter;
import cn.jinjimi.domain.data.dto.ClueDTO;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.CustomerStore;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.store.entity.ClueEntity;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.XListView.XListView;
import cn.jinjimi.app.main.widget.XRecyclerView.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * Created by Roy
 * Date: 16/12/30
 */

public class CustomerClueListFragment extends BaseFragment
        implements XRecyclerView.LoadingListener, XListView.IXListViewListener {
    public final static String SourceAll = "";
    public final static String SourceDrp = "drp";
    public final static String SourceRedPack = "redpack";
    public final static String SourceOther = "other";

    private XRecyclerView mRecyclerView;
    private CustomClueListAdapter mAdapter;
    private View emptyView;

    private String title;
    private String source;
    //首次进入显示缓存
    private boolean showCache = true;

    private int page = Constants.DEFAULT_PAGE;

    public CustomerClueListFragment() {
    }

    public static CustomerClueListFragment create(String title, String source) {
        CustomerClueListFragment customerClueListFragment = new CustomerClueListFragment();
        customerClueListFragment.setTitle(title);
        customerClueListFragment.setSource(source);
        return customerClueListFragment;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setSource(String source) {
        this.source = source;
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_clue_list;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    private void initView() {
        mRecyclerView = (XRecyclerView) findView().findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setLoadingMoreEnabled(false);
        mRecyclerView.setShowFooterWhenNoMore(true);

        emptyView = findView().findViewById(R.id.empty_view);

        mAdapter = new CustomClueListAdapter(getActivity());
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initListener() {
        mRecyclerView.setLoadingListener(this);
    }

    private void initData() {
        onRefresh();
    }

    @Override
    public void onRefresh() {
        getClueList(Constants.DEFAULT_PAGE);
    }

    @Override
    public void onLoadMore() {
        getClueList(page + 1);
    }

    private void getClueList(final int loadPage) {
        Task.callInBackground(new Callable<List<ClueEntity>>() {
            @Override
            public List<ClueEntity> call() throws Exception {
                if (loadPage == Constants.DEFAULT_PAGE && showCache) {
                    return DatabaseManager.getInstance().getClueEntityDao().queryClueEntities(source, Constants.PAGE_LIMIT_20);
                }
                return Collections.emptyList();
            }
        }).continueWith(new Continuation<List<ClueEntity>, Void>() {
            @Override
            public Void then(Task<List<ClueEntity>> task) throws Exception {
                if (showCache) {
                    showCache = false;
                    if (task.isCompleted() && task.getResult() != null)
                        mAdapter.setItems(task.getResult());
                }
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR).continueWith(new Continuation<Void, ClueDTO>() {
            @Override
            public ClueDTO then(Task<Void> task) throws Exception {
                ClueDTO mServerData = ServiceManager.getService(CustomerStore.class).getClues(loadPage, source);
                if (mServerData != null && mServerData.isOk &&
                        mServerData.data != null && !mServerData.data.isEmpty()) {
                    List<ClueEntity> mData = DatabaseManager.getInstance().getClueEntityDao().insertOrUpdate(mServerData.data);
                    mServerData.data = mData;
                }
                return mServerData;
            }
        }, Task.BACKGROUND_EXECUTOR).continueWith(new Continuation<ClueDTO, Void>() {
            @Override
            public Void then(Task<ClueDTO> task) throws Exception {
                if (task.isCompleted() && task.getResult().isOk) {
                    ClueDTO clues = task.getResult();
                    if (clues != null) {
                        if (loadPage == Constants.DEFAULT_PAGE) {
                            mAdapter.setItems(clues.data);
                        } else {
                            mAdapter.addItems(clues.data);
                        }
                        page = loadPage;
                        mRecyclerView.loadMoreComplete();
                        mRecyclerView.setLoadingMoreEnabled(clues.data != null && clues.data.size() == Constants.PAGE_LIMIT_20);
                        mRecyclerView.setShowFooterWhenNoMore(!mAdapter.isEmpty());
                        mRecyclerView.setNoMore((clues.data == null || clues.data.size() < Constants.PAGE_LIMIT_20));
                        onLoadComplete();
                    } else {
                        onFail();
                    }
                } else {
                    onFail();
                }
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }

    private void onFail() {
        if (getUserVisibleHint())
            ToastUtils.toastMessage(getContext(), R.string.load_fail);
        mRecyclerView.loadMoreComplete();
        onLoadComplete();
    }

    private void onLoadComplete() {
        emptyView.setVisibility(mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
        EventBus.getDefault().post(new CustomClueRefreshEvent(CustomClueRefreshEvent.TYPE_LIST));
    }

    public void onReceiveClueEvent(ClueUpdateEvent ev) {
        if (mAdapter == null) return;
        ClueEntity entity = ev.updatedClue;
        List<ClueEntity> mDatas = mAdapter.getItems();
        if (entity != null &&
                mDatas != null && !mDatas.isEmpty()) {
            String clueId = entity.clueId;
            for (int i = 0; i < mDatas.size(); i++) {
                if (clueId.equals(mDatas.get(i).clueId)) {
                    mAdapter.updateItem(i, entity);
                    return;
                }
            }
        }
    }

    @Override
    public String getTitle() {
        return title;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onClueAddCustomSucEvent(ClueAddCustomSucEvent event) {
        for (int i = 0; i < mAdapter.getItems().size(); i++) {
            if (mAdapter.getItem(i).clueId.equals(event.clue.clueId)) {
                mAdapter.remove(i, mRecyclerView.getHeadViewCount());
                mAdapter.insert(event.clue, i, mRecyclerView.getHeadViewCount());
                EventBus.getDefault().post(new CustomClueStaticUpdateEvent());
                break;
            }
        }
    }

    /* 监听客户资料的变化 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomChangeEvent(CustomChangeEvent event) {
        if (event.changeEvent == CustomChangeEvent.EVENT_DELETE) {
            for (int i = 0; i < mAdapter.getItems().size(); i++) {
                if (mAdapter.getItem(i).customerId == null)
                    continue;

                if (mAdapter.getItem(i).customerId.equals(String.valueOf(event.data.customerId))) {
                    ClueEntity clueEntity = mAdapter.getItem(i);
                    clueEntity.customerId = null;
                    mAdapter.remove(i, mRecyclerView.getHeadViewCount());
                    mAdapter.insert(clueEntity, i, mRecyclerView.getHeadViewCount());
                    EventBus.getDefault().post(new CustomClueStaticUpdateEvent());
                    break;
                }
            }
        }
    }
}
